package com.whut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whut.entity.Admin;
import com.whut.mapper.AdminMapper;
import com.whut.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {
    /**
     * 管理员登录
     * @param username
     * @param password
     * @return
     */
    public boolean login(String username, String password) {
        // 根据controller传递的用户名username查询数据库
        // 创建MyBatis-Plus的查询包装器
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        // 构造查询条件
        queryWrapper.eq(Admin::getUsername, username);
        Admin admin = this.getOne(queryWrapper);
        // 如果没有查询到则返回false
        if (admin == null) {
            return false;
        }
        // 比对密码是否正确 不正确则返回false

        if (!admin.getPassword().equals(password)) {
            return false;
        }
        // 如果用户名和密码都正确，则返回true
        return true;
    }

    /**
     * 更新管理员登录时间和ip
     * @param username
     * @param date
     */
    public void updateLoginTime(String username, LocalDateTime date) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        // 构造查询条件
        queryWrapper.eq(Admin::getUsername, username);
        Admin admin = this.getOne(queryWrapper);
        admin.setLoginTime(date);
        this.save(admin);
    }
}
